package com.caiheng.api.controller.platform;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.caiheng.api.constant.ResponseCode;
import com.caiheng.api.entity.platform.Coupons;
import com.caiheng.api.entity.wxuser.User;
import com.caiheng.api.entity.wxuser.UserCoupons;
import com.caiheng.api.service.platfom.CouponsService;
import com.caiheng.api.service.platfom.ParameterService;
import com.caiheng.api.service.wxuser.UserCouponsService;
import com.caiheng.api.service.wxuser.UserService;
import com.caiheng.api.util.GsonResultBean;
import com.caiheng.api.util.Tools;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

/**
 *@Author: ZhouWei
 *@Description:  用户技能相关接口
 *@Date 2018-05-10
 */
@Component
@RestController
@RequestMapping("/coupon")//url:模块/资源/{}/细分
public class CouponController extends BaseController {

    @Resource
    private UserService userService;
    @Resource
    private ParameterService parameterService;
    @Resource
    private CouponsService couponsService;
    @Resource
    private UserCouponsService userCouponsService;

    /**
     *  平台当前的优惠券列表
     * @param
     * @throws Exception
     */
    @PostMapping(value="/list")
    public JSONObject couponList(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "mer/coupon/user/list 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            Integer user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            Integer pageIndex = jsonRequest.containsKey("pageIndex")&& StrUtil.isNotEmpty(jsonRequest.get("pageIndex").toString())  ? jsonRequest.getInt("pageIndex") : 1;
            Integer pageSize = jsonRequest.containsKey("pageSize")&& StrUtil.isNotEmpty(jsonRequest.get("pageSize").toString())  ? jsonRequest.getInt("pageSize") : 10;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"该用户不存在"),true,true);
            }

            QueryWrapper<Coupons> qw = new QueryWrapper<>();
            qw.eq("state",0);
            List<Coupons> list = couponsService.getPageEntityList(qw,pageIndex,pageSize);

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",list.size(),list),false,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }



    /**
     *  通过跃豆购买优惠券
     * @param
     * @throws Exception
     */
    @PostMapping(value="/buyCouponByYd")
    public JSONObject buyCouponByYd(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "mer/coupon/user/list 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            Integer user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            Integer couponId = jsonRequest.containsKey("coupon_id") ? jsonRequest.getInt("coupon_id") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"该用户不存在"),true,true);
            }

            Coupons coupons = couponsService.findById(couponId);
            if(coupons == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"该券不存在"),true,true);
            }

            double price = coupons.getSinglePrice().doubleValue();
            double integral = user.getIntegral();
            if(integral < price){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"您的积分余额不足"),true,true);
            }

            int ret = couponsService.addCoupon(user,coupons);
            if(ret > 0){
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"兑换成功"),true,true);
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"兑换失败"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }



    /**
     * 商家的优惠券列表
     * @param
     * @throws Exception
     */
    @PostMapping(value="/user/list")
    public JSONObject couponUserList(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "coupon/user/list 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            Integer user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            Integer state = jsonRequest.containsKey("state") ? jsonRequest.getInt("state") : 1;
            int pageIndex = jsonRequest.containsKey("pageIndex")&& StrUtil.isNotEmpty(jsonRequest.get("pageIndex").toString()) ? jsonRequest.getInt("pageIndex") : 1;
            int pageSize = jsonRequest.containsKey("pageSize")&& StrUtil.isNotEmpty(jsonRequest.get("pageSize").toString()) ? jsonRequest.getInt("pageSize") : 10;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"该用户不存在"),true,true);
            }

            QueryWrapper<UserCoupons> qw = new QueryWrapper<>();
            qw.eq("user_id",user_id);
//            qw.eq("state",state);
            qw.orderByDesc("id");
            List<UserCoupons> list = userCouponsService.getPageEntityList(qw,pageIndex,pageSize);

            Map<String,Object> map = new HashMap<>();
            map.put("coupons",list);

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",list.size(),map),false,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }


}
